<script setup lang="ts">
import { ref,onMounted,onUpdated } from 'vue'
import * as Y from 'yjs'
import { WebrtcProvider } from 'y-webrtc'
import { QuillBinding } from 'y-quill'
import Quill from 'quill'
import QuillCursors from 'quill-cursors'
import '../../../node_modules/quill/dist/quill.snow.css'
// import '../../../node_modules/quill/dist/quill.bubble.css'

let isShow = ref(false);

let isInit=false;

let showView=()=>{
    if(isInit){
        return;
    }
    isInit=true;

    Quill.register('modules/cursors', QuillCursors)

    const quill = new Quill(document.querySelector('#editor3'), {
    modules: {
        cursors: true,
        toolbar: [
        // adding some basic Quill content features
        [{ header: [1, 2, false] }],
        ['bold', 'italic', 'underline'],
        ['image', 'code-block']
        ],
        history: {
        // Local undo shouldn't undo changes
        // from remote users
        userOnly: true
        }
    },
    placeholder: 'Start collaborating...',
    theme: 'snow' // snow,'bubble' is also great
    })

    // A Yjs document holds the shared data
    const ydoc = new Y.Doc()


    let opts={
        // Specify signaling servers. The client will connect to every signaling server concurrently to find other peers as fast as possible.
        // 指定信号服务器。客户端将同时连接到每个信令服务器，以尽可能快地找到其他对等端。
        signaling: ['ws://localhost:4444'],

        // If password is a string, it will be used to encrypt all communication over the signaling servers.
        // No sensitive information (WebRTC connection info, shared data) will be shared over the signaling servers.
        // The main objective is to prevent man-in-the-middle attacks and to allow you to securely use public / untrusted signaling instances.
        // 如果密码是一个字符串，它将用于加密通过信号服务器的所有通信。
        // 不会在信号服务器上共享任何敏感信息（WebRTC连接信息、共享数据）。
        // 主要目标是防止中间人攻击，并允许您安全地使用公共/不受信任的信号实例。
        password: undefined,

        // Specify an existing Awareness instance - see https://github.com/yjs/y-protocols
        // 指定现有的Awareness实例
        // awareness: new awarenessProtocol.Awareness(doc),

        // Maximal number of WebRTC connections.
        // A random factor is recommended, because it reduces the chance that n clients form a cluster.
        //WebRTC连接的最大数量。
        //建议使用随机因素，因为这样可以减少n个客户端形成集群的机会。
        maxConns: 1, //20 + math.floor(random.rand() * 15),

        // Whether to disable WebRTC connections to other tabs in the same browser.
        // Tabs within the same browser share document updates using BroadcastChannels.
        // WebRTC connections within the same browser are therefore only necessary if you want to share video information too.
        // 是否禁用与同一浏览器中其他选项卡的WebRTC连接。
        // 同一浏览器中的选项卡使用BroadcastChannels共享文档更新。
        // 因此，只有当您也想共享视频信息时，才需要在同一浏览器内进行WebRTC连接。
        filterBcConns: true,

        // simple-peer options. See https://github.com/feross/simple-peer#peer--new-peeropts for available options.
        // y-webrtc uses simple-peer internally as a library to create WebRTC connections.
        peerOpts: {}
    };

    const provider = new WebrtcProvider('quill-editor-room-1', ydoc,opts);

    // Define a shared text type on the document
    const ytext = ydoc.getText('quill')

    // "Bind" the quill editor to a Yjs text type.
    const binding = new QuillBinding(ytext, quill, provider.awareness)

    // Remove the selection when the iframe is blurred
    window.addEventListener('blur', () => { quill.blur() })
    
    // enable logging for all modules
    window.localStorage.log = 'false';

    // enable logging only for y-webrtc
    // localStorage.log = 'y-webrtc'

    // by specifying a regex variables
    // localStorage.log = '^y.*'
}

onMounted(()=>{
    
})

onUpdated(()=>{
    if(isShow.value==true){
        showView();
    }
})

</script>

<template>
    <div class="hide"><input type="button" :value="`${isShow ? 'hide' : 'show'} yjs 3`" @click="isShow = !isShow"></div>
    <div v-show ="isShow">
        <div class="desc">Y JS 示例 ：Quill 编辑器集成 + Y-WebRTC,需要执行 yarn run webrtc</div>
        <div id="editor3" class="editor"></div>
    </div>
</template>

<style scoped>
/* @import './styles/katex.min.css'; */
/* @import './styles/monokai-sublime.min.css'; */

.editor{
    width:600px;
    height:400px;
}
</style>